package com.suapi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suapi.project.common.ErrorCode;
import com.suapi.project.exception.BusinessException;
import com.suapi.project.mapper.UserInterfaceInfoMapper;
import com.suapi.project.model.dto.userInterfaceInfo.UserInterfaceInfoVOQueryRequest;
import com.suapi.project.model.enums.UserInterfaceInfoStatusEnum;
import com.suapi.project.model.vo.UserInterfaceInfoVO;
import com.suapi.project.service.UserInterfaceInfoService;
import com.suapi.suapicommon.model.entity.UserInterfaceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author xidian
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2025-04-09 16:02:35
*/
@Slf4j
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        Integer totalNum = userInterfaceInfo.getTotalNum();

        // 创建时，所有参数必须非空
        log.info(String.valueOf(userInterfaceInfo));
        if (add) {
            if (userId < 0 || interfaceInfoId < 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户或接口不存在");
            }
        }
        if (userInterfaceInfo.getLeftNum() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"剩余次数不能小于0");
        }
        //TODO 要其他的规则后面再加
    }

    /**
     * 判断用户是否还有调用次数
     * @param interfaceInfoId
     * @param userId
     * @return
     */
//    @Override
//    public boolean isHaveTimes(long interfaceInfoId, long userId) {
//        LambdaQueryWrapper<UserInterfaceInfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(UserInterfaceInfo::getUserId,userId);
//        wrapper.eq(UserInterfaceInfo::getInterfaceInfoId,interfaceInfoId);
//        UserInterfaceInfo userInterfaceInfo = this.getOne(wrapper);
//        if (userInterfaceInfo == null){
//            return false;
//        }
//        if (userInterfaceInfo.getLeftNum() <= 0){
//            return false;
//        }
//        return true;
//    }

    @Override
    public int isHaveTimes(long interfaceInfoId, long userId) {
        LambdaQueryWrapper<UserInterfaceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInterfaceInfo::getUserId,userId);
        wrapper.eq(UserInterfaceInfo::getInterfaceInfoId,interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(wrapper);
        if (userInterfaceInfo == null){
            return -1;
        }
        if (userInterfaceInfo.getLeftNum() <= 0){
            return 0;
        }
        return userInterfaceInfo.getLeftNum();
    }

    /**
     * 获取状态
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public int getUserInterfaceInfoStatus(long interfaceInfoId, long userId) {
        LambdaQueryWrapper<UserInterfaceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(UserInterfaceInfo::getStatus);
        wrapper.eq(UserInterfaceInfo::getUserId,userId);
        wrapper.eq(UserInterfaceInfo::getInterfaceInfoId,interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(wrapper);
        return userInterfaceInfo.getStatus();
    }

    /**
     * 调用次数
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId, int haveTimes) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 此处使用乐观锁来保证数据一致性
        UpdateWrapper<UserInterfaceInfo> userInterfaceInfoUpdateWrapper = new UpdateWrapper<>();
        userInterfaceInfoUpdateWrapper.eq("interfaceInfoId", interfaceInfoId);
        userInterfaceInfoUpdateWrapper.eq("userId", userId);
        userInterfaceInfoUpdateWrapper.eq("leftNum", haveTimes);
        userInterfaceInfoUpdateWrapper.setSql("leftNum = leftNum - 1,totalNum = totalNum + 1");
        //userInterfaceInfoUpdateWrapper.gt("leftNum", 0);
        boolean b = this.update(userInterfaceInfoUpdateWrapper);
        return b;
    }

    /**
     * 分页获取列表，联合查询（任何人可以访问）
     * @param userInterfaceInfoVOQueryRequest
     * @return
     */
    @Override
    public Page<UserInterfaceInfoVO> listUserInterfaceInfoVOByPage(UserInterfaceInfoVOQueryRequest userInterfaceInfoVOQueryRequest) {
        // 获取分页参数
        long current = userInterfaceInfoVOQueryRequest.getCurrent();
        long pageSize = userInterfaceInfoVOQueryRequest.getPageSize();

        Page<UserInterfaceInfoVO> page = new Page<>(current, pageSize);
        Page<UserInterfaceInfoVO> resultPage =
                userInterfaceInfoMapper.selectUserInterfaceInfoVOListByPage(page, userInterfaceInfoVOQueryRequest);
        log.info("resultPage:{}",resultPage.getRecords());
        //userInterfaceInfoVOPage.setRecords(userInterfaceInfoVOList);
        return resultPage;
    }

    /**
     * 修改状态（仅管理员访问）
     * @param id
     * @return
     */
    @Override
    public Boolean alertUserInterfaceInfoStatus(Long id) {
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoMapper.selectById(id);
        if (userInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"用户未开通本接口");
        }
        if (userInterfaceInfo.getStatus() == UserInterfaceInfoStatusEnum.on.getValue()){
            userInterfaceInfo.setStatus(UserInterfaceInfoStatusEnum.off.getValue());
        }else {
            userInterfaceInfo.setStatus(UserInterfaceInfoStatusEnum.on.getValue());
        }
        boolean b = this.updateById(userInterfaceInfo);
        if (!b){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

}




